#include "qNalogkorekcija.h"
#include <QItemSelectionModel>
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRecord>
#include "chelperclass.h"
#include <QDesktopWidget>


QNalogKorekcija::QNalogKorekcija(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,selRow(-1)
    ,textId("")
    ,komintentID("")
    ,artikal_id(0)
    , pItemDelegate(0)
    , editorOpen(0)
{
    ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.lineEdit->setFocus();
    ui.lineEdit->setText("");
	ui.lineEdit->setStyleSheet("background-color: yellow");
    
    ui.lineEdit_2->setText("");
	ui.lineEdit->installEventFilter(this);
	ui.lineEdit_2->installEventFilter(this);
	ui.lineEdit_3->installEventFilter(this);
	ui.lineEdit_4->installEventFilter(this);
	ui.lineEdit_5->installEventFilter(this);
    ui.dateTimeEdit->installEventFilter(this);

	connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(on_pushButton_clicked()));
    connect(ui.lineEdit_2, SIGNAL(returnPressed()), this, SLOT(on_pushButton_2_clicked()));
    connect(ui.lineEdit_3, SIGNAL(returnPressed()), this, SLOT(on_plineEdit3_Pressed()));
    connect(ui.lineEdit_4, SIGNAL(returnPressed()), this, SLOT(on_plineEdit4_Pressed()));

    pItemDelegate = new QSTableWidgetDelegate(ui.tableView);
    pComboItemDelegate = new QComboBoxItemDelegate(ui.tableView_2);
    connect(pComboItemDelegate, SIGNAL(updatePodatoci()), this , SLOT(updatePodatoci()));
    connect(ui.tableView_2 ,SIGNAL(doubleClicked (const QModelIndex & )),this ,SLOT(slotDoubleMC(const QModelIndex &)));
    connect(this ,SIGNAL(editCell()),this,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this,SLOT(closeEditor()));

    ui.tableView->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui.tableView->setItemDelegate(pItemDelegate);
    ui.tableView_2->setItemDelegate(pComboItemDelegate);

	model = new QStandardItemModel(0,7);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Цена"));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Ид.1"));

	ui.tableView->setSortingEnabled(true);
	ui.tableView_2->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
    header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
    header->show();
    m_chc = new CHelperClass(NULL);
    m_chc->createSaldoMap(0);

}

QNalogKorekcija::~QNalogKorekcija()
{
    delete m_chc;
}
void QNalogKorekcija::pressEscape()
{
    if (ui.lineEdit_2->hasFocus())
    {
        ui.pushButton_4->setFocus();
        ui.pushButton_4->setChecked(true);
    }
    else
    {
        emit closeW();
    }
}
void QNalogKorekcija::on_pushButton_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isKomintentExists(ui.lineEdit->text()))
    {
        emit scallKomintenti((QWidget*)this, ui.lineEdit->text());
    }
    else
    {
        ui.lineEdit_2->setFocus();
    }
}

void QNalogKorekcija::setFocusLine()
{
	ui.lineEdit->setFocus();
}
void QNalogKorekcija::setKomintent(QString text, QString textName)
{
	ui.lineEdit->setText(textName);
	komintentID = text;
}

void QNalogKorekcija::setArtikli(QString text, QString textName)
{
	ui.lineEdit_2->setText(textName);
	textId = text;
    artikal_id = text.toInt();

    QSqlQuery query;
    query.prepare("select art_prodazna_cena_valuta from artikli where id = :id");
    query.bindValue(":id", artikal_id);	
    query.exec();
    query.next();
    ui.lineEdit_3->setText(query.value(0).toString());

}

void QNalogKorekcija::setFocusLine2()
{
	ui.lineEdit_2->setFocus();
}

void QNalogKorekcija::on_pushButton_2_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit_2->text());
    }
    else
    {
        ui.lineEdit_4->setFocus();
    }
}



void QNalogKorekcija::on_pushButton_3_clicked()
{
	CHelperClass hclass(this);
	QString keyItem = hclass.GetRandomString();
	if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_2->setFocus();
		return;
	}


	QLocale loc;
	if(textId.toInt() == -1)
	{
		return;
	}

	//m_id = textId.toInt();

	QString temp = "select id, sifra, artikal, edm from artikli where id =";
	temp += textId;
	QSqlQuery query(temp);
	QString country1 = "";
	QString country2 = "";
	QString country3 = "";
	QString country4 = "";
	while (query.next()) {
		country1 = query.value(query.record().indexOf("id")).toString();
		country2 = query.value(query.record().indexOf("sifra")).toString();
		country3 = query.value(query.record().indexOf("artikal")).toString();
		country4 = query.value(query.record().indexOf("edm")).toString();
		//        ui.lineEdit->setText(country1);
	}

	int row = model->rowCount();

	QStandardItem *item = new QStandardItem(country1);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(0, 40);
	model->setItem(row, 0, item);

	item = new QStandardItem(country2);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(1, 70);
	model->setItem(row, 1, item);

	item = new QStandardItem(country3);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 220);
	model->setItem(row, 2, item);

	item = new QStandardItem(country4);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(3, 60);
	model->setItem(row, 3, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_4->text().toFloat(), 'f', 2));
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(4, 100);
	model->setItem(row, 4, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_3->text().toFloat(), 'f', 2));
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(5, 100);
	model->setItem(row, 5, item);

	item = new QStandardItem(keyItem);
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(6, 0);
	model->setItem(row, 6, item);

	ui.tableView->setModel(model);
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();

	insertDetalMap(country1, keyItem);
	m_vkkol = ui.lineEdit_4->text().toFloat();
	ui.lineEdit_2->setText("");
	ui.lineEdit_3->setText("");
	ui.lineEdit_4->setText("");
	ui.lineEdit_2->setFocus();
	textId = "-1";


}

void QNalogKorekcija::selectionChanged(QModelIndex modelX,QModelIndex modelY)
{
	//save state here...
	selRow = modelX.row();

	int i = modelX.row();
	m_selectedText = model->item(i, 6) ? model->item(i, 6)->text():"";
	lista_detail(m_selectedText);
	emit closeCell();
}

void QNalogKorekcija::insertDetalMap(QString mId, QString keyString)
{
    QString temp = 
        " SELECT artikli.id, artikli.sifra, artikli.artikal, artikli.edm, proizvodi_sostav.kolicina, artikli.kategorija "
        " FROM proizvodi_sostav "
        " LEFT JOIN artikli ON proizvodi_sostav.id_artikal = artikli.id "
        " WHERE proizvodi_sostav.id_proizvod = ";
    temp += mId;

    QSqlQuery query(temp);
    std::vector<sostavInfo> mVectorArtSostav;
    mVectorArtSostav.clear();
    QLocale loc;

    while (query.next()) 
    {
        sostavInfo mArtSost;
        mArtSost.aId = query.value(0).toString();
        mArtSost.aSifra = query.value(1).toString();
        mArtSost.aArtikal = query.value(2).toString();
        float kol = query.value(4).toFloat();
        float num = ui.lineEdit_4->text().toFloat();

        mArtSost.aEdm = query.value(3).toString();
        mArtSost.aKol = loc.toString(kol * num, 'f', 2);
        mArtSost.aInfo = query.value(5).toString();
		mArtSost.aProizvodId = mId;
        mVectorArtSostav.push_back(mArtSost);
    }
    mListArtikli.insert(std::pair<QString, std::vector<sostavInfo>>(keyString, mVectorArtSostav));
}

void QNalogKorekcija::on_pushButton_6_clicked()
{
    std::map<QString, std::vector<sostavInfo>>::iterator it;
    it = mListArtikli.find(m_selectedText);
    if (it != mListArtikli.end())
    {
        mListArtikli.erase (it);       
    }
	QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
    model->removeRow(indexes.at(0).row());
    lista_detail(m_selectedText);
}
void QNalogKorekcija::pressReturn()
{
    if (ui.pushButton_3->hasFocus())
    {
        on_pushButton_3_clicked();
    }
    else if (ui.pushButton_6->hasFocus())
    {
        on_pushButton_6_clicked();
    }
    else if (ui.tableView->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
        }
        else
        {
            emit editCell();
        }
        editorOpen = !editorOpen;
    }
}

//////////////////////

void QNalogKorekcija::insertInitialDetailMap(QString proizvod_id, QString dok_id, QString keyId)
{
	CHelperClass *hlp = new CHelperClass(this);
	int sub_tip = hlp->checkIfArtikalIsProizvod(proizvod_id) ? 1 : 0;   // 1 == proizvod // 0 == artikal
	delete hlp;
	if (!sub_tip)
	{
		return;
	}
	
	QString temp = 
        " SELECT artikli.id, artikli.sifra, artikli.artikal, artikli.edm, magacin.ikol, artikli.kategorija, magacin.proizvod_id "
        " FROM magacin "
        " LEFT JOIN artikli ON magacin.artikal_id = artikli.id "
        " WHERE magacin.dok_tip = 41 AND magacin.dok_id = "+ dok_id +" AND magacin.proizvod_id = '" + keyId +"'";

    QSqlQuery query(temp);
    std::vector<sostavInfo> mVectorArtSostav;
    mVectorArtSostav.clear();

    while (query.next()) 
    {
        sostavInfo mArtSost;

        mArtSost.aId = query.value(0).toString();
        mArtSost.aSifra = query.value(1).toString();
        mArtSost.aArtikal = query.value(2).toString();
        mArtSost.aEdm = query.value(3).toString();
        mArtSost.aKol = query.value(4).toString();
        mArtSost.aInfo = query.value(5).toString();

        mVectorArtSostav.push_back(mArtSost);
    }
    mListArtikli.insert(std::pair<QString, std::vector<sostavInfo>>(keyId, mVectorArtSostav));
}


void QNalogKorekcija::init(int id)
{
    QLocale loc;
    if(id == -1)
    {
        return;
    }
    m_id = id;
    ui.lineEdit_5->setText(QString::number(id, 10));
    QString temp1 = 
        "select dokumenti.id, komintenti.id , komintenti.naziv, dokumenti.datum, dokumenti.doc_creator, dok_opis "
        "from dokumenti "
        "left join komintenti on dokumenti.komintent_id = komintenti.id "
        "where dokumenti.dok_tip = 22 and dokumenti.dok_id = ";        
    temp1 += QString::number(id, 10);
    QSqlQuery query1(temp1);
    while (query1.next())
    {
        ui.lineEdit->setText(query1.value(2).toString().isEmpty() ? "" : query1.value(2).toString());
        komintentID = query1.value(1).toString();
        dokumentID = query1.value(0).toString();
        QString a = query1.value(0).toString();
		ui.dateTimeEdit->setDate(query1.value(3).toDate());
        ui.plainTextEdit->setPlainText(query1.value(5).toString());
    }

    int r = 0;
    int c = 7;
    int fieldNo[7];
    QString country[7];
    int colWidth[] = {40, 70, 220, 60, 100, 100, 0};
    QString colName[] = {"id", "sifra", "artikal", "edm", "ikol", "icena", "id1" };
    QString temp = 
        "select artikli.id, sifra, artikal, edm, ikol, icena, proizvod_id "
        "from magacin "
        "left join artikli on magacin.artikal_id=artikli.id "
        "where magacin.dok_tip = 22 and magacin.dok_id= ";
    temp += QString::number(id, 10);
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
    model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
    model->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
    model->setHeaderData( 5, Qt::Horizontal, trUtf8("Цена"));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Ид1"));

	ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
	QString tempKey = "";
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = NULL;
			if(i == 6)
			{
				QString tempKey = query.value(i).toString();
				item = new QStandardItem(tempKey);
				item->setTextAlignment(Qt::AlignLeft);
			}
			else
			{
				
				QString temp = query.value(i).toString();
				if (i > 3)
				{
					temp =  loc.toString(temp.toFloat(), 'f', 2);
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignRight);
				}
				else
				{
					item = new QStandardItem(temp);
					item->setTextAlignment(Qt::AlignLeft);
				}
				
			}
			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
        }
        insertInitialDetailMap(query.value(0).toString(), QString::number(id, 10), query.value(6).toString());
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
    ui.lineEdit->setFocus();
}

void QNalogKorekcija::on_pushButton_5_clicked()
{
	pressEscape();
}

void QNalogKorekcija::pressF9()
{
	on_pushButton_4_clicked();
}

void QNalogKorekcija::on_pushButton_4_clicked()
{
    QLocale loc;
    if (!validateKomintent())
    {
        QMessageBox msgBox;
        msgBox.setText(trUtf8("Податокот за коминтент е невалиден\nОдбери коминтент од листата на коминтенти!"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
        ui.lineEdit->setFocus();
        return;
    }

    int mmid = m_id;
    int cols = model->columnCount();
    int rows = model->rowCount();
    if (!rows)
    {
        return;
    }

    int mid=0;
    QSqlDatabase db = QSqlDatabase::database();
    db.transaction();	
    bool sqlStat = true;

    QSqlQuery query1;
    query1.clear();
    query1.prepare("update dokumenti set dok_id = :a0, datum=:a1, faktura_id=:a2, mag_id=:a3, komintent_id=:a4, dok_opis = :a5 where id=:aid and dok_tip = 22");
    query1.bindValue(":a0", ui.lineEdit_5->text());	
    query1.bindValue(":a1", ui.dateTimeEdit->dateTime());	
    query1.bindValue(":a2", 0);	
    query1.bindValue(":a3", 0);	
    query1.bindValue(":a4", komintentID);	
    query1.bindValue(":a5", ui.plainTextEdit->toPlainText());	

    query1.bindValue(":aid", dokumentID);	
    sqlStat = sqlStat && query1.exec();
    QSqlError err = query1.lastError();

    query1.clear();
    query1.prepare("delete from magacin where (dok_tip = 22 or dok_tip = 41) and dok_id = :a");
    query1.bindValue(":a", mmid);	
    sqlStat = sqlStat && query1.exec();

    query1.clear();
    query1.prepare("delete from magacin where dok_tip = 41 and dok_id = :a");
    query1.bindValue(":a", mmid);	
    sqlStat = sqlStat && query1.exec();


    int row = model->rowCount();
    // Vnesi zapis vo tabela na dokumenti (za naracka stavi tip na dokument 22)

	for (int i = 0; i < rows; i++)
	{

		QString mArtikalID = model->item(i, 0)->text();
		QString mArtikalSifra = model->item(i, 1)->text();
		QString mArtikalNaziv = model->item(i, 2)->text();
		QString mArtikalEdm = model->item(i, 3)->text();
		QString mArtikalKolicina = model->item(i, 4)->text();
		QString mArtikalCena = model->item(i, 5)->text();
		QString mProizvod = model->item(i, 6)->text();


		// Sub_tip -ot oznacuva dali e proizvod ili artikal
		CHelperClass *hlp = new CHelperClass(this);
		int sub_tip = hlp->checkIfArtikalIsProizvod(mArtikalID) ? 1 : 0;   // 1 == proizvod so normativ // 0 == artikal repro
		delete hlp;

		query1.clear();
		query1.prepare(
			"insert into magacin(dok_id, dok_tip, artikal_id, ikol, icena, rabat, sub_tip, mag_id, proizvod_id, dok_tip_link) "
			"values(:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9,:a10)"
			);
		query1.bindValue(":a1", m_id);	
		query1.bindValue(":a2", 22);	
		query1.bindValue(":a3", mArtikalID);	
		query1.bindValue(":a4", loc.toFloat(mArtikalKolicina));	
		query1.bindValue(":a5", loc.toFloat(mArtikalCena));	
		query1.bindValue(":a6", 0);	
		query1.bindValue(":a7", sub_tip);	
		query1.bindValue(":a8", 2);	
		query1.bindValue(":a9", mProizvod);	
		query1.bindValue(":a10", 22);	
		sqlStat = sqlStat && query1.exec();

		if (!sub_tip)
		{
			query1.clear();
			query1.prepare(
				"insert into magacin(dok_id, dok_tip, artikal_id, ikol, icena, rabat, sub_tip, mag_id, proizvod_id, dok_tip_link) "
				"values(:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9,:a10)"
				);
			query1.bindValue(":a1", m_id);	
			query1.bindValue(":a2", 41);	
			query1.bindValue(":a3", mArtikalID);	
			query1.bindValue(":a4", loc.toFloat(mArtikalKolicina));	
			query1.bindValue(":a5", loc.toFloat(mArtikalCena));	
			query1.bindValue(":a6", 0);	
			query1.bindValue(":a7", sub_tip);	
			query1.bindValue(":a8", 0);	
			query1.bindValue(":a9", mProizvod);
			query1.bindValue(":a10", 22);	
			sqlStat = sqlStat && query1.exec();
		}
	}

	std::map<QString, std::vector<sostavInfo>>::iterator it;
	for (it = mListArtikli.begin(); it != mListArtikli.end(); it++)
	{
		std::vector<sostavInfo> vItemList = it->second;
		for (int k = 0; k < vItemList.size(); k++)
		{
			query1.clear();
			query1.prepare(
				"insert into magacin(dok_id, dok_tip, artikal_id, ikol, icena, rabat, sub_tip, mag_id, proizvod_id, dok_tip_link) "
				"values(:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9,:a10)"
				);
			query1.bindValue(":a1", m_id);	
			query1.bindValue(":a2", 41);	
			query1.bindValue(":a3", vItemList.at(k).aId);	
			query1.bindValue(":a4", loc.toFloat(vItemList.at(k).aKol));	
			query1.bindValue(":a5", loc.toFloat(0));	
			query1.bindValue(":a6", 0);	
			query1.bindValue(":a7", 0);	
			query1.bindValue(":a8", 0);	
			query1.bindValue(":a9", it->first);	
			query1.bindValue(":a10", 22);	
			sqlStat = sqlStat && query1.exec();
		}
	}

	err = query1.lastError();

    if (sqlStat)
    {
        db.commit();
        QMessageBox msgBox;
        msgBox.setText(trUtf8("Налогот е успешно корегиран."));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
        pressEscape();
    }
    else
    {
        db.rollback();
        QMessageBox msgBox;
        msgBox.setText(trUtf8("Налогот НЕ Е корегиран. !!!."));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
    }
}

bool QNalogKorekcija::existDok(int idDok)
{
    int nCount = 0;
    QString temp = "select count(dok_id) br from dokumenti where dok_tip = 22 and dok_id =";
    temp += QString::number(idDok, 10);
    QSqlQuery query(temp);
    QString country1 = "";
    int fieldNo = query.record().indexOf("br");
    while (query.next()) {
        nCount = query.value(0).toInt() + 1;
    }
    return nCount > 0 ? true : false;
}

bool QNalogKorekcija::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::FocusIn)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_5)
		{
			ui.lineEdit_5->setStyleSheet("background-color: yellow");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: yellow");
        }

	}
	if (event->type() == QEvent::FocusOut)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_5)
		{
			ui.lineEdit_5->setStyleSheet("background-color: none");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: none");
        }
	}

	return false;
}

void QNalogKorekcija::on_plineEdit3_Pressed()
{
    ui.lineEdit_4->setFocus();
}
void QNalogKorekcija::on_plineEdit4_Pressed()
{
    on_pushButton_3_clicked();
}
void QNalogKorekcija::openEditor()
{
    //	tableView->closePersistentEditor(indexPrev);
    if (ui.tableView->hasFocus())
    {
        QModelIndex index;
        QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
        index = indexes.at(0);	// To get the row/column numbers use 
        if (index.column() > 3)
        {
            //ui.tableView->openPersistentEditor(index);
        }
        indexPrev = index;
    } 
    else
    {
        QModelIndex indexTable2;
        QModelIndexList indexes2 = ui.tableView_2->selectionModel()->selection().indexes();
        indexTable2 = indexes2.at(0);	// To get the row/column numbers use 
        if (indexTable2.column() > 0)
        {
            ui.tableView_2->openPersistentEditor(indexTable2);
        }
        indexPrevTable2 = indexTable2;
    }
}

void QNalogKorekcija::closeEditor()
{
    ui.tableView->closePersistentEditor(indexPrev);
    ui.tableView_2->closePersistentEditor(indexPrevTable2);
    editorOpen = false;
}

bool QNalogKorekcija::validateKomintent()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isKomintentExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}


void QNalogKorekcija::slotDoubleMC(const QModelIndex & ind)
{
    if (editorOpen)
    {
        emit closeCell();
    }
    else
    {
        emit editCell();
    }
    editorOpen = !editorOpen;
}
void QNalogKorekcija::lista_detail(const QString& nameSearch)
{
    bool ok1;
    float kolMusterija = m_vkkol;
    pComboItemDelegate->setKolicinaMusterija(kolMusterija);
    QLocale loc;
    if (nameSearch.length() < 0)
    {
        ui.tableView_2->hide();
        return;
    }
    std::map<QString, std::vector<sostavInfo>>::iterator it;
    it = mListArtikli.find(nameSearch);
    model2 = new QStandardItemModel(0, 7);
    ui.tableView_2->setModel(model2);
    model2->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
    model2->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
    model2->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
    model2->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
    model2->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
    model2->setHeaderData( 5, Qt::Horizontal, trUtf8("Количина во магацин на артикли"));
    model2->setHeaderData( 6, Qt::Horizontal, trUtf8("Инфо"));    
    if(it != mListArtikli.end())
    {
        std::vector<sostavInfo> vList = (*it).second; 
        int i = 0;

        int rowAll = vList.size();
        model2->setRowCount(rowAll);

        for (int i = 0; i < rowAll; i++)
        {
            sostavInfo itemQuery = vList.at(i);
            float saldo = 0; 
            float kolvk = 0;
            QBrush newBrush;
            


            QStandardItem *item = new QStandardItem(itemQuery.aId);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(0, 0);
            model2->setItem(i, 0, item);

            item = new QStandardItem(itemQuery.aSifra);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(1, 50);
            model2->setItem(i, 1, item);

            item = new QStandardItem(itemQuery.aArtikal);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(2, 250);
            model2->setItem(i, 2, item);
           
            if (itemQuery.aInfo.toInt())
            {
                QIcon ic1(":/sterna/Resources/arrow-down-icon.png");
                item->setIcon(ic1);   
            }

            item = new QStandardItem(itemQuery.aEdm);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(3, 50);
            model2->setItem(i, 3, item);

            item = new QStandardItem(loc.toString(itemQuery.aKol.toFloat(), 'f', 2));
            item->setTextAlignment(Qt::AlignRight);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(4, 80);
            model2->setItem(i, 4, item);

            saldo = m_chc->getLagerLista(itemQuery.aId , (QString)"ART_PRILIV") - 
                m_chc->getLagerLista(itemQuery.aId , (QString)"ART_ODLIV"); 
            item = new QStandardItem(loc.toString(saldo, 'f', 2));
            item->setTextAlignment(Qt::AlignRight);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(5, 250);
            model2->setItem(i, 5, item);


            item = new QStandardItem(itemQuery.aInfo);
            item->setTextAlignment(Qt::AlignRight);
            item->setEditable(false);
            ui.tableView_2->setRowHeight(i, 18);
            ui.tableView_2->setColumnWidth(6, 50);
            model2->setItem(i, 6, item);

            if (saldo >= itemQuery.aKol.toFloat())
            {
                QIcon ic1(":/sterna/Resources/ok.png");
                item->setIcon(ic1);
            }
            else
            {
                QIcon ic1(":/sterna/Resources/stop.png");
                item->setIcon(ic1);
            }

        } 
        ui.tableView_2->setModel(model2);
        QItemSelectionModel *sm = ui.tableView_2->selectionModel();
        connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            this, SLOT(selectionChangedDetail(QModelIndex,QModelIndex)));
        ui.tableView_2->show();
    }
}

void QNalogKorekcija::selectionChangedDetail(QModelIndex modelX,QModelIndex modelY)
{
    if (editorOpen)
    {
        emit closeEditor();
    }
}

void QNalogKorekcija::updatePodatoci()
{
    int r = model2->rowCount();
    int c = model2->columnCount();
    std::vector<sostavInfo> vItemList;
    for (int i = 0; i < r; i++)
    {
        sostavInfo itemTemp;
        itemTemp.aId = model2->item(i, 0)->text();
        itemTemp.aSifra = model2->item(i, 1)->text();
        itemTemp.aArtikal = model2->item(i, 2)->text();
        itemTemp.aEdm = model2->item(i, 3)->text();
        itemTemp.aKol = model2->item(i, 4)->text();
        itemTemp.aKolMagArt = model2->item(i, 5)->text();
        itemTemp.aInfo = model2->item(i, 6)->text();
        
        vItemList.push_back(itemTemp);
    }
    std::map<QString, std::vector<sostavInfo>>::iterator it;
    it = mListArtikli.find(m_selectedText);
    if (it != mListArtikli.end())
    {
        it->second = vItemList;
        lista_detail(m_selectedText);
    }
}